package com.bf.xpdd.web.controller.front;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bf.xpdd.domain.ActivityRecordBean;
import com.bf.xpdd.domain.BidCache;
import com.bf.xpdd.domain.FrontBean;
import com.bf.xpdd.domain.JSONResponse;
import com.bf.xpdd.domain.SiteBuyer;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.domain.SiteShop;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.service.AccountService;
import com.bf.xpdd.service.ActivityRecordService;
import com.bf.xpdd.service.FrontService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.Constant;
import com.bf.xpdd.util.JSONTranslator;

/**
 * 
 * front controller
 * 
 * @author Fantastic
 * @version 1.0.0
 * @since 1.0.0
 */
@Controller
@RequestMapping(value = "/front")
public class FrontController
{
	/** front service */
	@Autowired
	private FrontService frontService;
	
	/** taobao service */
	@Autowired
	private TaobaoService taobaoService;
	
	/** account service */
	@Autowired
	private AccountService accountService;
	
	/** Activity Record Service */
	@Autowired
	private ActivityRecordService activityRecordService;
	
	/**
	 * default frame
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String showDefault(HttpServletRequest request)
	{
		//TODO: 验证登录， 判断页面类型，返回默认界面
//		String nick = ((Seller)request.getSession().getAttribute("seller")).getNick();
//		try
//		{
//			FrontBean front = this.frontService.findFrontActivity(nick);
//			System.out.println(front);
//		}
//		catch (BaseException e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return "front/front_item";
	}
	
	/**
	 * show post
	 * 
	 * @return xml
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/global")
	public String showGlobal(HttpServletRequest request, @RequestParam Map<String, String> params)
	{
		//返回参数
		JSONResponse response = new JSONResponse();
		try 
		{
			//将页面店铺、买家信息存入session
			SiteShop shop = JSONTranslator.toBean(com.bf.xpdd.util.Base64.decode(params.get("shop")), SiteShop.class);
			SiteBuyer buyer = JSONTranslator.toBean(com.bf.xpdd.util.Base64.decode(params.get("buyer")), SiteBuyer.class);
			request.getSession().setAttribute("shop", shop);
			request.getSession().setAttribute("buyer", buyer);
			//查询交互界面信息
			String json = JSONTranslator.toJSON(frontService.findFrontActivity(shop.getSellerNick(), 0, 6), "utf-8", "utf-8");
			response.setCode("0");
			response.setJson(json);
			return response.toString();
		} 
		catch (BaseException e) 
		{
			e.getStackTrace();
			response.setCode("-1");
			response.setMessage(e.getMessage());
			return response.toString();
		} 
		catch (UnsupportedEncodingException e) 
		{
			response.setCode("-7");
			response.setMessage(e.getMessage());
			return response.toString();
		}
	}

	/**
	 * show post
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/play")
	public String show(HttpServletRequest request)
	{
		JSONResponse jsonResponse = new JSONResponse();
		
		//TODO: 请求返回公告信息
		try 
		{
			//店铺信息
			SiteShop shop = (SiteShop) request.getSession().getAttribute("shop");
			//商品id
			String itemId = request.getParameter("dItem").toString();
			//买家信息
			SiteBuyer buyer = (SiteBuyer) request.getSession().getAttribute("buyer");
			//交互界面信息
			FrontBean front = frontService.findFrontItemDetail(shop.getSellerNick(), itemId);
			//创建砍价缓存信息
			Map<String, BidCache> bidMap = buyer.getBidMap();
			if(!bidMap.containsKey(itemId))
			{
				BidCache bidCache = new BidCache();
				bidCache.setCurrentPrice(Double.parseDouble(front.getItemList().get(0).getPrice()));
				bidCache.setBidCount(0);
				buyer.getBidMap().put(itemId, bidCache);
			}
			
			//剩余时间 日 小时 分钟
			request.setAttribute("rday", front.getRemainingTime().getTime() / 1000 / 60 / 60 / 24);
			request.setAttribute("rhour", (front.getRemainingTime().getTime() % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			request.setAttribute("rminute", (front.getRemainingTime().getTime() % (1000 * 60 * 60)) / (1000 * 60));
			//前台数据
			request.setAttribute("font", front);
			//错误提示
			request.setAttribute("error", "");
			//商品信息
			request.setAttribute("item", front.getItemList().get(0));
			//出价记录 v1.0.0 中实际为成交记录
			request.setAttribute("bidList", front.getBidList());
		} 
		catch (BaseException e) 
		{
			jsonResponse.setCode("-2");
			jsonResponse.setMessage("请求失败，请联系管理员。");
			return jsonResponse.toString();
		}
		return "front/front_play";
	}

	/**
	 * bid
	 * 
	 * @return xml
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/bid")
	public String requestBid(HttpServletRequest request, @RequestParam Map<String, String> params)
	{
		JSONResponse jsonResponse = new JSONResponse();
		try 
		{
			
			//商品id
			long itemId = Long.parseLong(params.get("itemId"));
			
			//买家信息
			SiteBuyer buyer = (SiteBuyer) request.getSession().getAttribute("buyer");
			
			//已经有成交记录了 不再砍价 找人帮忙吧
			if(0 > this.activityRecordService.queryActRecordByItemIdAndNick(itemId, buyer.getNick()))
			{
				jsonResponse.setCode("-2");
				jsonResponse.setMessage("您已经血拼过该宝贝了，快找人帮忙吧！！");
				return jsonResponse.toString();
			}
			
			int plan = Integer.parseInt(params.get("plan"));
			double price = Double.parseDouble(params.get("price"));
			
			String json = JSONTranslator.toJSON(this.frontService.bargain(itemId, price, plan, buyer), "utf-8", "utf-8");
			jsonResponse.setCode("0");
			jsonResponse.setJson(json);
			jsonResponse.setMessage("砍价成功");
			return jsonResponse.toString();
		} 
		catch (BaseException e) 
		{
			jsonResponse.setCode("-1");
			jsonResponse.setMessage("请求失败，请联系管理员。");
			return jsonResponse.toString();
		}
		
	}
	
	/**
	 * show post
	 * 
	 * @return xml
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/deal")
	public String requestDeal(HttpServletRequest request)
	{
		JSONResponse jsonResponse = new JSONResponse();
		LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();
		
		SiteSeller seller;
		try 
		{
			//itemId --> promotion --> discountValue --> itemDetailUrl
			SiteBuyer buyer = (SiteBuyer) request.getSession().getAttribute("buyer");
			String itemId = request.getParameter("itemId");
			String itemName = request.getParameter("itemName");
			
			//已经有成交记录了 不再砍价 找人帮忙吧
			if(0 < this.activityRecordService.queryActRecordByItemIdAndNick(Long.parseLong(itemId), buyer.getNick()))
			{
				jsonResponse.setCode("-2");
				jsonResponse.setMessage("您已经血拼过该宝贝了，快找人帮忙吧！！");
				return jsonResponse.toString();
			}
			
			//获取商品相应的优惠链接
			SiteShop shop = (SiteShop) request.getSession().getAttribute("shop");
			BidCache cache = buyer.getBidMap().get(itemId);
			jsonResponse.setCode("-3");
			jsonResponse.setMessage("未正确初始化砍价商品。");
			
			seller = this.accountService.findSessionKeyByNick(shop.getSellerNick());
			if(null == seller)
			{
				//生成成交记录
				ActivityRecordBean record = this.frontService.findActivityRecordInfoByItem(itemId);
				record.setBuyerNick(buyer.getNick());
				record.setItemName(itemName);
				record.setPrice(cache.getCurrentPrice());
				record.setBuyNum(1);
				record.setRecordTime(new Date());
				record.setToperId(0);
				record.setBidPrice(cache.getBid());
				record.setStatus(Constant.TAG_USER_NOT_ADDED);
				record.setDiscount(cache.getTaobaoDiscount() * 10);
				this.activityRecordService.addActivityRecord(record);
				
				//返回界面信息
				jsonResponse.setCode("2");
				jsonResponse.setMessage("服务器繁忙，活动记录已产生，请联系掌柜的同步您的折扣信息，然后享受血拼价。");
			}
			else
			{
				String result = this.taobaoService.findPromotionByItemId(seller.getTopSession(), Long.parseLong(itemId));
				LinkedHashMap map = JSONTranslator.toBean(result, LinkedHashMap.class);
				ArrayList<LinkedHashMap> promotionList = (ArrayList) ((LinkedHashMap)((LinkedHashMap) map.get("marketing_promotions_get_response")).get("promotions")).get("promotion");
				for(LinkedHashMap tempMap : promotionList)
				{
					String discountValue = tempMap.get("discount_value").toString();
					String itemDetailUrl = tempMap.get("item_detail_url").toString();
					String tagId = tempMap.get("tag_id").toString();
					if(Double.parseDouble(discountValue) == cache.getTaobaoDiscount() * 10)
					{
						this.taobaoService.addTagBuyer(seller.getTopSession(), Long.parseLong(tagId), buyer.getNick());
						resultMap.put("dealUrl", itemDetailUrl);
						jsonResponse.setCode("0");
						jsonResponse.setJson(JSONTranslator.toJSON(resultMap));
						jsonResponse.setMessage("成交！您可以点击宝贝图片开始购买，或者直接刷新该宝贝的详情页面。");
						//生成成交记录
						ActivityRecordBean record = this.frontService.findActivityRecordInfoByItem(itemId);
						record.setBuyerNick(buyer.getNick());
						record.setItemName(itemName);
						record.setPrice(cache.getCurrentPrice());
						record.setBuyNum(1);
						record.setRecordTime(new Date());
						record.setToperId(0);
						record.setBidPrice(cache.getBid());
						record.setStatus(Constant.TAG_USER_ADDED);
						record.setDiscount(cache.getTaobaoDiscount() * 10);
						this.activityRecordService.addActivityRecord(record);
						break;
					}
				}
			}
		} 
		catch (BaseException e) 
		{
			jsonResponse.setCode("-1");
			jsonResponse.setMessage("请求失败，请联系管理员。");
			return jsonResponse.toString();
		} 
		
		return jsonResponse.toString();
	}
	
	/**
	 * show post
	 * 
	 * @return xml
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/post")
	public String showPost(HttpServletRequest request)
	{
		//TODO: 请求返回公告信息
		return "post";
	}
	
	/**
	 * show rule
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/rule")
	public String showRule(HttpServletRequest request)
	{
		//TODO: 请求返回规则信息
		return "rule";
	}
	
	/**
	 * show rule
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/test")
	public String showTest(HttpServletRequest request)
	{
		//TODO: 请求返回规则信息
		return "test";
	}
	
	/**
	 * show pact
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/pact")
	public String showPact(HttpServletRequest request)
	{
		//TODO: 请求返回协议信息
		return "pact";
	}
	
	/**
	 * 收藏店铺
	 * 
	 * @return page
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/favorite")
	public String keepStore(HttpServletRequest request)
	{
		JSONResponse jsonResponse = new JSONResponse();
		try
		{
			SiteShop shop = (SiteShop) request.getSession().getAttribute("shop");
			SiteBuyer buyer = (SiteBuyer) request.getSession().getAttribute("buyer");
			this.taobaoService.addFavorite(shop, buyer);
			jsonResponse.setCode("0");
			jsonResponse.setMessage("砍价成功");
			return jsonResponse.toString();
		}
		catch(Exception e)
		{
			jsonResponse.setCode("-1");
			jsonResponse.setMessage("收藏失败");
			return jsonResponse.toString();
		}
	}
	
	/**
	 * share current page
	 * 
	 * @return page
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/share")
	public String shareItem(HttpServletRequest request)
	{
		//TODO: 请求分享当前页面
		return "share";
	}
	
	/**
	 * show Community
	 * 
	 * @return page
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/community")
	public String showCommunity(HttpServletRequest request)
	{
		//TODO: 请求社区
		return "Community";
	}
	
	/**
	 * show post
	 * 
	 * @return xml
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/showMoreItem")
	public String showMoreItem(HttpServletRequest request, @RequestParam Map<String, String> params)
	{
		//返回参数
		JSONResponse response = new JSONResponse();
		try 
		{
			//将页面店铺、买家信息存入session
			SiteShop shop = (SiteShop) request.getSession().getAttribute("shop");
			
			int start = Integer.parseInt(params.get("start").toString());
			
			int len = 6;
			
			//查询交互界面信息
			String json = JSONTranslator.toJSON(frontService.findFrontActivity(shop.getSellerNick(), start, len), "utf-8", "utf-8");
			response.setCode("0");
			response.setJson(json);
			return response.toString();
		} 
		catch (Exception e)
		{
			response.setCode("-1");
			response.setMessage(e.getMessage());
			return response.toString();
		} 
	}
	
	/**
	 * show detail frame
	 * 
	 * @return xml
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/detail")
	public String showDetailFrame(HttpServletRequest request)
	{
		//TODO: 商品详情界面，以及相关操作请求
		return "front/front_play";
	}
	
}
